<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>

        //将'a=1&b=2&c=3'  变成{a:1,b:2,c:3}

        function parse(str) {
            let obj = {}
            let args = str.split('&') //['a=1','b=2','c=3']
            args.forEach(function (item) {
                let kv = item.split('=') //['a',1],['b',2]
                let key = kv[0]
                let val = kv[1]
                obj[key] = val //obj['a']=1  obj['b']=2
            })
            return obj
        }

        // console.log(parse('a=1&b=2&c=3'));
        // console.log(parse('a=21&b=23'));
        // console.log(parse('age=21&name=Simba'));

        //将{a:1,b:2,c:3}  变成'a=1&b=2&c=3'  
        function stringify(obj) {
            let arr = []
            //for-in遍历对象的所有属性
            for (let key in obj) {
                let val = obj[key]//对象[属性名]=>属性值
                let str = key + '=' + val //a=1 
                arr.push(str);
            }
            return arr.join('&')
        }


        // function stringify(obj) {
        //     let arr = []
        //     //for-in遍历对象的所有属性
        //     Object.keys(obj).forEach(function (key) {
        //         let val = obj[key]//对象[属性名]=>属性值
        //         let str = key + '=' + val //a=1 
        //         arr.push(str);
        //     })

        //     return arr.join('&')
        // }

        // function stringify(obj) {
        //     //for-in遍历对象的所有属性
        //     let arr = Object.keys(obj).map(function (key) {
        //         let val = obj[key]//对象[属性名]=>属性值
        //         let str = key + '=' + val //a=1 
        //         return str
        //     })
        //     return arr.join('&')
        // }

        // let stringify = obj => Object.keys(obj).map(key => key + '=' + obj[key]).join('&')

        let zz = {
            a: 1,
            b: 2,
            c: 3
        }
        console.log(stringify(zz));
        console.log(stringify({ aa: 1, age: 2 }));
        console.log(stringify({ name: 'ace', age: 20 }));

    </script>
</body>

</html>